package com.yonyou.gmmc.service.pointactivity.service;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.service.pointactivity.dao.NotReturnFactoryMapper;
import com.yonyou.gmmc.service.pointactivity.dao.ReservationMapper;
import com.yonyou.gmmc.service.pointactivity.dao.TtOwnerLotteryMapper;
import com.yonyou.gmmc.service.pointactivity.model.TmReturnFactory;
import com.yonyou.gmmc.service.pointactivity.model.TmSweepstake;
import com.yonyou.gmmc.service.pointactivity.model.TtOwnerLottery;
import com.yonyou.gmmc.service.pointactivity.util.DateUtils;


@Transactional
@Service("LotteryService")
public class LotteryService {
	
	@Autowired
	private TtOwnerLotteryMapper ttOwnerLotteryMapper;
	
	@Autowired
	private ReservationMapper reservationMapper;
	
	@Autowired
	private NotReturnFactoryMapper notReturnFactoryMapper;

	/**
	 * 按中奖率抽奖
	 * @param vin 
	 * @param num 中奖百分比 50---50%中奖率
	 * @return 中奖结果 true/false
	 */
	public boolean ifWinLottery(String openId,int drawProbability, String vin){
		 Random ra =new Random();
		 int number = ra.nextInt(100)+1;
		 System.out.println("================================="+number);
		 if(number > 0 && number <= drawProbability){
			 return true;
			 }
		 insertTtOwnerLotteryNo(openId,vin);
		 return false;
	}
	
	
	/**
	 * 判断当前是否有抽奖名额 ----当前总抽奖率是否已达到
	 * @param qtnNo 
	 * @param vin 
	 * @return 
	 */
	public boolean ifCanDrawLottery(String openId, String qtnNo, String vin){
		//获取总抽奖率
		int totalProbability = ttOwnerLotteryMapper.getTotalProbability();
		//查询现有中奖数与奖券总数的比例
		double totalProportion = ttOwnerLotteryMapper.getTotalProportion();
		//判断是否有抽奖名额,如果有，查询个人中奖率
		if(totalProbability > totalProportion){
			int personalProbability = 0;
			if("12".equals(qtnNo)){
				personalProbability = ttOwnerLotteryMapper.getPersonnalProbability();
			}
			else{
				personalProbability = ttOwnerLotteryMapper.getLowPersonnalProbability();
			}
			return ifWinLottery(openId,personalProbability,vin);
			}
		insertTtOwnerLotteryNo(openId,vin);
		return false;
	}
	
	/**
	 * 奖券分布
	 */
	public synchronized void lotteryDistribute(int paramDay){
		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 Date endDate = null;
		 try {
			 endDate = format.parse(getDrawEndTime());
			 } 
		 catch (ParseException e) {
				 e.printStackTrace();
				 }
		int day = DateUtils.getDaysInMonth(new Date());
		//A部分823张按未返厂客户省份 占比分
		if(paramDay == 99){
			day = 1;
		}
		if(day == 1){
			deleteALottery();
			getPartAProportion();
			setPartBLottery();
			}
		else if(day > 1 && day < DateUtils.getDaysInMonth(endDate) - 3){
			int sumPlan = 400;
			if(day != 2){
				sumPlan = countBLottery();
				}
			int sumFact = 0;
			List<TmReturnFactory> list = ttOwnerLotteryMapper.getPartBProportion();
			if(list != null){
				for (TmReturnFactory tmReturnFactory : list) {
					float a = (tmReturnFactory.getProportion() * sumPlan / 100);
					int i = Math.round(a);
					sumFact += i;
					tmReturnFactory.setLotteries(i);
					}
				if(sumPlan - sumFact != 0){
					list.get(0).setLotteries(list.get(0).getLotteries() + sumPlan - sumFact);
					}
				deleteBLottery();
				for (TmReturnFactory tmReturnFactory : list) {
					int sum = tmReturnFactory.getLotteries();
					TmSweepstake sweepstake=new TmSweepstake();
					for(int j = 0; j < sum; j++){
						sweepstake.setCreateDate(new Date());
						sweepstake.setTmSweepstakeProvince(tmReturnFactory.getFactoryProvinceName());
						sweepstake.setTmSweepstakeState("1");
						sweepstake.setUpdateDate(new Date());
						reservationMapper.allotLotteries(sweepstake);
						}
					}
				}
			}
		else{
			ttOwnerLotteryMapper.updateLotteryProvince();
			}
		}
	
	
	/**
	 * 查询A部分奖券占比  按省份分配奖券
	 * @return A
	 */
	public void getPartAProportion(){
		int sumPlan = 823;
		int sumFact = 0;
		List<TmReturnFactory> list = ttOwnerLotteryMapper.getPartAProportion();
		if(list != null){
			for (TmReturnFactory tmReturnFactory : list) {
				sumFact += tmReturnFactory.getLotteries();
				}
			if(sumPlan - sumFact != 0){
				list.get(0).setLotteries(list.get(0).getLotteries() + sumPlan - sumFact);
				}
		}
		
		for (TmReturnFactory tmReturnFactory : list) {
			int sum = tmReturnFactory.getLotteries();
			TmSweepstake sweepstake=new TmSweepstake();
			for(int j = 0; j < sum; j++){
				sweepstake.setCreateDate(new Date());
				sweepstake.setTmSweepstakeProvince(tmReturnFactory.getFactoryProvinceName());
				sweepstake.setTmSweepstakeState("2");
				sweepstake.setUpdateDate(new Date());
				reservationMapper.allotLotteries(sweepstake);
				}
			}
		}
	
	/**
	 * 查询B部分奖券占比  按省份分配奖券
	 * @return B
	 */
	public void setPartBLottery(){
			int sum = 400;
			for(int i=0;i<sum;i++){
				TmSweepstake sweepstake=new TmSweepstake();
				sweepstake=new TmSweepstake();
				sweepstake.setTmSweepstakeProvince("");
				sweepstake.setCreateDate(new Date());
				sweepstake.setTmSweepstakeState("1");
				sweepstake.setUpdateDate(new Date());
				reservationMapper.allotLotteries(sweepstake);
				}
		}
	
	
	/**
	 * 查询B部分奖券占比
	 * @return B部分奖券占比
	 */
	public List<TmReturnFactory> getPartBProportion(){
		return ttOwnerLotteryMapper.getPartBProportion();
	}
	
	
	/**
	 * 查询B部分奖券数
	 * @return
	 */
	public int countBLottery(){
		return ttOwnerLotteryMapper.countBLottery();
		}
	
	
	/**
	 * 删除B部分奖券
	 */
	public void deleteBLottery(){
		ttOwnerLotteryMapper.deleteBLottery();
		}
	
	/**
	 * 删除A部分奖券
	 */
	public void deleteALottery(){
		ttOwnerLotteryMapper.deleteALottery();
		}
	
	/**
	 * 获得所在省份对应的奖券
	 */
	public List<TmSweepstake> getLotteryByProvince(String province){
		List<TmSweepstake> listRs =  ttOwnerLotteryMapper.getLotteryByProvince(province);
		return listRs;
		}
	
	/**
	 * 获得未抽取的奖券
	 */
	public List<TmSweepstake> getLottery(){
		List<TmSweepstake> listRs =  ttOwnerLotteryMapper.getLottery();
		return listRs;
		}
	
	/**
	 * 获得客户参与活动登录省份
	 * @return 客户参与活动省份
	 */
	public String getUserProvince(String openId){
		String province = ttOwnerLotteryMapper.getUserProvinceByOpenId(openId);
		return province;
		}
	
	/**
	 * 添加中奖纪录
	 * @param openId
	 * @param vin 
	 * @return 是否新增
	 */
	public synchronized String insertTtOwnerLottery(String openId,String province, String vin){
		TtOwnerLottery ttOwnerLottery = new TtOwnerLottery();
		List<TmSweepstake> list = getLotteryByProvince(province);
		int count = ttOwnerLotteryMapper.countTtOwnerLottery();
		if(list.size() > 0 && count < 1223){
			String lotteryId = list.get(0).getTmSweepstakeKey();
			ttOwnerLottery.setLotteryId(lotteryId);
			ttOwnerLottery.setOpenId(openId);
			ttOwnerLottery.setVin(vin);
			ttOwnerLottery.setProvince(province);
			ttOwnerLottery.setCreateDate(new Date());
			ttOwnerLottery.setUpdateDate(new Date());
			ttOwnerLottery.setOrderStatus("0");
			ttOwnerLottery.setCreateBy("");
			ttOwnerLottery.setUpdateBy("");
			ttOwnerLotteryMapper.insert(ttOwnerLottery);
			ttOwnerLotteryMapper.updateTtSweepstakeByKey(lotteryId);
			return "YES";
			}
		insertTtOwnerLotteryNo(openId,vin);
		return "NO";
		}
	
	/**
	 * 插入未中奖纪录
	 * @param vin 
	 * @return 
	 */
	public synchronized void insertTtOwnerLotteryNo(String openId, String vin){
		TtOwnerLottery ttOwnerLottery = new TtOwnerLottery();
		ttOwnerLottery.setLotteryId("NO");
		ttOwnerLottery.setOpenId(openId);
		ttOwnerLottery.setProvince("");
		ttOwnerLottery.setVin(vin);
		ttOwnerLottery.setOrderStatus("0");
		ttOwnerLottery.setCreateDate(new Date());
		ttOwnerLottery.setUpdateDate(new Date());
		ttOwnerLottery.setCreateBy("");
		ttOwnerLottery.setUpdateBy("");
		ttOwnerLotteryMapper.insert(ttOwnerLottery);
		}
	
	/**
	 * 抽奖不限中奖率和省份比例
	 * @param openId
	 * @param vin 
	 * @return
	 */
	public synchronized String drawWithoutProbabilityandProportion(String openId, String vin){
			TtOwnerLottery ttOwnerLottery = new TtOwnerLottery();
			List<TmSweepstake> list = ttOwnerLotteryMapper.getLotterys();
			int count = ttOwnerLotteryMapper.countTtOwnerLottery();
			if(list.size() > 0 && count < 1223){
				String lotteryId = list.get(0).getTmSweepstakeKey();
				ttOwnerLottery.setLotteryId(lotteryId);
				ttOwnerLottery.setVin(vin);
				ttOwnerLottery.setOpenId(openId);
				ttOwnerLottery.setProvince("不限");
				ttOwnerLottery.setCreateDate(new Date());
				ttOwnerLottery.setUpdateDate(new Date());
				ttOwnerLottery.setOrderStatus("0");
				ttOwnerLottery.setCreateBy("");
				ttOwnerLottery.setUpdateBy("");
				ttOwnerLotteryMapper.insert(ttOwnerLottery);
				ttOwnerLotteryMapper.updateTtSweepstakeByKey(lotteryId);
				return "YES";
				}
			insertTtOwnerLotteryNo(openId,vin);
			return "NO";
		}
	
	/**
	 * 根据客户openId查询中奖信息
	 */
	public TmSweepstake findByLottery(String openId){
		TmSweepstake sweepstake=null;
		if (openId!=null) { 
			String vin = ttOwnerLotteryMapper.getVinByOpenId(openId);
			Map<String, Object> param = new HashMap<>();
			param.put("openId", openId);
			param.put("vin", vin);
			sweepstake=ttOwnerLotteryMapper.getLotter(param);
			} 
		return sweepstake;
		}
	
	/**
	 * 抽奖流程
	 * @param openId
	 * @param qtnNo 
	 * @throws ParseException 
	 */
	public String drawLottery(String openId,String province, String qtnNo) throws ParseException{
		//判断是否抽过
		//根据活动天数设置抽奖方式
		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 Date endDate = null;
		 try {
			 endDate = format.parse(getDrawEndTime());
			 } 
		 catch (ParseException e) {
				 e.printStackTrace();
				 }
		String vin = ttOwnerLotteryMapper.getVinByOpenId(openId);
		if(DateUtils.getDaysInMonth(new Date()) >= DateUtils.getDaysInMonth(endDate)-3 && "12".equals(qtnNo)){
			//活动最后三天不设中奖率、不限省份
			return drawWithoutProbabilityandProportion(openId,vin);
			}
		else{
			//之前设置中奖率，判断是否中奖
			if(ifCanDrawLottery(openId,qtnNo,vin)){
				return insertTtOwnerLottery(openId,province,vin);
				}
			else{
				return "NO";
				}
			}
		}
	
	/**
	 *  是否抽过奖
	 * @param openId
	 * @return
	 */
	public String ifDrawLottery(String openId){
		boolean ifWin = Boolean.valueOf(notReturnFactoryMapper.isExtract(openId));
		if(ifWin){
			String vin = ttOwnerLotteryMapper.getVinByOpenId(openId);
			Map<String, Object> param = new HashMap<>();
			param.put("openId", openId);
			param.put("vin", vin);
			Map<String, Object> map = ttOwnerLotteryMapper.queryTtOwnerLotteryByOpenId(param);
			String lotteryId = map.get("LOTTERY_ID").toString();
			if("NO".equals(lotteryId)){
				return "YN";
				}
			return "YY";
			}
		return "NO";
		}
	
	
	public String getDrawEndTime(){
		String endTime = ttOwnerLotteryMapper.getDrawEndTime();
		return endTime;
	}
	

}


